package com.hunk.core.auth.service;

import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hunk.core.auth.dao.UserDao;
import com.hunk.core.auth.entity.User;
import com.hunk.core.web.model.Page;
import com.hunk.utils.exception.CustomizeException;

/**
 * Description :<br>
 * 
 * @author HunkDeng
 * @since 2013-4-14
 */
//@Service
public class AuthService {
	
	@Autowired
	private UserDao userDao;	
	/**
	 * @author HunkDeng
	 * @param user
	 * @return
	 * @throws CustomizeException
	 */
	public User checkUser(User user) throws CustomizeException {
		User _user = userDao.getUserByName(user);
		if (_user == null) {
			throw new CustomizeException("用户不存在");
		} else {
			if (StringUtils.equals(user.getPassword(), _user.getPassword())) {
				return _user;
			} else {
				throw new CustomizeException("密码错误");
			}
		}
	}	
	/**
	 * @author HunkDeng
	 * @param reqPage
	 * @return
	 */
	public Page<User> getPage(Page<User> reqPage) {
		String queryString = " " + UserDao.SYS_USER;
		String countString = "select count(id) from "+UserDao.SYS_USER;
		return userDao.getPageModel(reqPage, 
				new StringBuilder(queryString), 
				new StringBuilder(countString), 
				new StringBuilder(""), 
				new ArrayList<Object>(), User.class);
	}
	
	/**
	 * @author HunkDeng
	 * @param user
	 * @return
	 * @throws CustomizeException
	 */
	public User saveOrUpdateUser(User user) throws CustomizeException {
		try {
			if(user.getId() != null)
				return userDao.update(user);
			else
				return userDao.save(user);
		} catch (SQLException e) {
			throw new CustomizeException("操作失败:" + e.getMessage());
		}
	}
	
	/**
	 * @author HunkDeng
	 * @param user
	 * @throws CustomizeException
	 */
	public void deleteUser(User user) throws CustomizeException {
		try {
			userDao.delete(user);
		} catch (SQLException e) {
			throw new CustomizeException("操作失败:" + e.getMessage());
		}
	}
}
